//
//  AppDelegate.m
//  MonitoringSystem
//
//
//
//                            _ooOoo_
//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                            O\ = /O
//                        ____/`---'\____
//                      .   ' \\| |// `.
//                       / \\||| : |||// \
//                     / _||||| -:- |||||- \
//                       | | \\\ - /// | |
//                     | \_| ''\---/'' | |
//                      \ .-\__ `-` ___/-. /
//                   ___`. .' /--.--\ `. . __
//                ."" '< `.___\_<|>_/___.' >'"".
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |
//                 \ \ `-. \_ __\ /__ _/ .-` / /
//         ======`-.____`-.___\_____/___.-`____.-'======
//                            `=---='
//
//         .............................................
//                  佛祖保佑             永无BUG
#import "AppDelegate.h"
#import <SMS_SDK/SMSSDK.h>
#import <SDWebImage/SDImageCache.h>
#import "ACDeviceController.h"
#import "ACUserLoginManage.h"
#import "ACMainViewController.h"
#import "ACNewGuidController.h"
#import "ACUserLoginManage.h"
#import "UtilToolsClass.h"
#import "JPUSHService.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate ()<UIAlertViewDelegate,JPUSHRegisterDelegate>
@end
@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 启动页的时候隐藏导航条
    [application setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    NSLog(@"launchOptions :%@",launchOptions);
    // 统一按钮的clear的样式 自定义清楚按钮
    [self setUpTextFieldClearnButton];
    
    // 更新cookit操作
    [self updateSession];
    
    //初始化SMSDK   ------------ 用于短信验证
    [SMSSDK registerApp:MOBSMSAPPKEY withSecret:MOBSMSAPPSECRET];
    
    // 初始化JPush
    [self initJPush:launchOptions];
    
    // 清楚缓存
    [self clearTmpPics];
    
    // 选择根控制器
    [self chooseRootViewControlller];
    
    // app崩溃信息 ---- 统计消息都是迟一天上传后台
    [self initUMCrash];
    

    return YES;
}

- (void) initUMCrash{
    [JPUSHService crashLogON];
}



- (void) chooseRootViewControlller{
     self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    // 取出当前软件版本号
    NSString *curVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    // 取出上次手动存储的版本号
    NSString *oldVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"VersionKey"];
    // 比对当前软件是否第一次打开
    if ([curVersion isEqual:oldVersion]){
        NSLog(@"没有新特性");
       // 已经登录过---直接进入设备列表界面，如果退出了登陆，那么下次进来也是登陆界面.
        // 在loginVC控制器，viewWillAppear中设置登录标识loginManage.loginTag 为0;
        UIStoryboard * storyboard;
         ACUserLoginManage * loginManage = [ACUserLoginManage shareInstance];
        if ([loginManage.loginTag intValue]) {
            storyboard =  [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            self.window.rootViewController = [storyboard instantiateInitialViewController];
        }else{
            // 在登录界面，需不需要展示新特性功能
            UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
             self.window.rootViewController = [storyBoard instantiateInitialViewController];
        }
    } else {
        NSLog(@"有新特性");
        // 手动将当前版本存入偏好设置
        [UD setValue:curVersion forKey:@"VersionKey"];
        ACNewGuidController * newGuidController = [[ACNewGuidController alloc] init];
        self.window.rootViewController = newGuidController;
    }
    [self.window makeKeyWindow];
    [self.window makeKeyAndVisible];
}


-(void)applicationDidBecomeActive:(UIApplication *)application{
    [UD setObject:@(0) forKey:@"applicationIconBadgeNumber"];
    application.applicationIconBadgeNumber = 0;
}

#pragma mark 清除缓存
- (void)clearTmpPics{
    
    [[SDImageCache sharedImageCache] clearDisk];
    [[SDImageCache sharedImageCache] clearMemory];//可有可无
}


#pragma mark 内存警告
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application{
    
    [[SDImageCache sharedImageCache] clearDisk];
    [[SDImageCache sharedImageCache] clearMemory];//可有可无
}

#pragma mark 设置textField上的清除按钮的样式
-(void) setUpTextFieldClearnButton {
    UIButton *defaultClearButton = [UIButton appearanceWhenContainedIn:[UITextField class], nil];
    defaultClearButton = [UIButton appearanceWhenContainedIn:[UITextField class], nil];
    [defaultClearButton setBackgroundImage:[UIImage imageNamed:@"TextfiledClose"] forState:UIControlStateNormal];
}

/**
 *  http://www.jianshu.com/p/65094611980c
 *
 *  cookie的操作.更新cookie。在程序每次启动的时候调用一下。用来确保每次的cookie是最新的。
 */
- (void) updateSession{
    NSDictionary * cookitDic =  [UD dictionaryForKey:acLocalCookieName];
    NSDictionary * cookitProperties = [cookitDic valueForKey:acCookitDict];
    if (cookitProperties != nil) {
        NSHTTPCookie * cookie = [NSHTTPCookie cookieWithProperties:cookitProperties];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }
}


#pragma mark - jPush  升级到iOS10兼容推送
- (void)initJPush:(NSDictionary *)launchOptions {
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
    } else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:JPushAppKey
                          channel:JPushChannel
                 apsForProduction:JPushApsForProduction
            advertisingIdentifier:nil];
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkDidReceiveMessage:)
                                                 name:kJPFNetworkDidReceiveMessageNotification
                                               object:nil];
}

// 获取deviceToken并上传到极光
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
 
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    // Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}


// deviceToken获取失败的回调
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    // 推送错误调用
    NSLog(@"push error : %@",error);
}

// iOS7接收到推送的处理方法
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
       [JPUSHService handleRemoteNotification:userInfo];
       //可以添加自定义categories
      [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |UIUserNotificationTypeSound |UIUserNotificationTypeAlert)
                                                   categories:nil];
 
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
     NSLog(@"this is iOS7 Remote Notification");
        // IOS 7 Support Required
        [JPUSHService handleRemoteNotification:userInfo];
        completionHandler(UIBackgroundFetchResultNewData);
    
    NSDictionary * aps = [userInfo objectForKey:@"aps"];
    [JPUSHService setBadge:[[aps objectForKey:@"badge"] integerValue]];
    [UIApplication sharedApplication].applicationIconBadgeNumber = [[aps objectForKey:@"badge"] integerValue];
    
}
#endif

// 接收到消息的处理方法。
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSLog(@"notification：%@",notification);
    // 获取推送的内容
    @try {
        NSDictionary * contentDic = (NSDictionary *)notification.userInfo[@"extras"] ;
        if ([[ACUserLoginManage shareInstance].userCode isEqualToString:contentDic[@"account"]]) {
            // 符合推送timestampStringTransformDateString
            NSString * showTime = [UtilToolsClass timestampStringTransformFullDataString:[contentDic[@"pushtime"] longLongValue] ];
            [self showAlertWithPushDeviceContent:[contentDic[@"acResult"] integerValue] message:contentDic[@"msg"] time:showTime];
        }
    } @catch (NSException *exception) {
        NSLog(@"推送发生异常：exception  %@:",exception);
    } @finally {
        [JPUSHService crashLogON];
    }
}



/**
 *  根据推送的内容显示不一样的框  0-管理员转移   1-非作业状态推送   2-马达故障推送
 */
- (void) showAlertWithPushDeviceContent:(NSInteger) result message:(NSString *)message time:(NSString *) pushtime{
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    UIAlertView *alertView = [[UIAlertView alloc] init];
    alertView.title = NSLocalizedString(@"接收到一条消息",nil);
    alertView.delegate = self;
    if (result == 0) {
        [alertView addButtonWithTitle:NSLocalizedString(@"确定",nil)];
        alertView.message = [NSString stringWithFormat:@"%@ %@%@ %@",NSLocalizedString(@"您已成为设备",nil),message,NSLocalizedString(@"的管理者",nil),pushtime];
    }else if(result == 1 ){
     
        [alertView addButtonWithTitle:NSLocalizedString(@"确定",nil)];
        alertView.message = [NSString stringWithFormat:@"%@:%@ %@ %@",NSLocalizedString(@"设备编号为",nil),message,NSLocalizedString(@"的设备进入非作业状态",nil),pushtime];
    }else if(result == 2){
      
        [alertView addButtonWithTitle:NSLocalizedString(@"确定",nil)];
        if ([UtilToolsClass judgeLocalLanguage] == 1) {
            alertView.message = [NSString stringWithFormat:@"设备编号为:%@的设备进入马达故障状态! %@",message,pushtime];
        }else{
            alertView.message = [NSString stringWithFormat:@"Pump %@ motor failure! %@",message,pushtime];
        }
    }else if(result == 3){
     
        [alertView addButtonWithTitle:NSLocalizedString(@"确定",nil)];
        if ([UtilToolsClass judgeLocalLanguage] == 1) {
            alertView.message = [NSString stringWithFormat:@"设备编号为:%@的设备进入低油位状态 %@",message,pushtime];
        }else{
            alertView.message = [NSString stringWithFormat:@"Lubricant of Pump:%@ reaches  low  level! %@",message,pushtime];
        }
    }
    alertView.tag = result;
    [alertView show];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
     if ([[UD objectForKey:@"isNeedRefreshWithView"] intValue]) {
         if(alertView.tag == 0){
             // 权限转移下来
             // 点击确定，刷新设备列表.storyboard
             UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
             [[[UIApplication sharedApplication] delegate] window].rootViewController =  [storyBoard instantiateInitialViewController];
         }else  if(alertView.tag == 1 || alertView.tag == 2 || alertView.tag == 3){
             // 故障、非作业下来
             UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
             [[[UIApplication sharedApplication] delegate] window].rootViewController =  [storyBoard instantiateInitialViewController];
             
         }
     }
}


// iOS 10接收通知，在此方法可以对通知内容进行处理
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 前台收到远程通知:%@", userInfo);
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    /*
        需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置.
        如果在前台不需要apns提醒，那么将如下的代码注释掉即可
     */
//    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
}


// 点击apns通知后的回调此方法，这边可以做处理，此外，要注意同时可以接受到消息networkDidReceiveMessage
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        // 在此不做任何处理，因为后台自定义的消息内容才是我们要的
        NSLog(@"iOS10 收到远程通知:%@",userInfo);
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}
#endif




- (void)applicationWillResignActive:(UIApplication *)application {}
- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
}
- (void)applicationWillTerminate:(UIApplication *)application {}
@end
